﻿using UnityEngine;
using System.Collections;

public interface I_CSSRule
{
    bool Match(ReadOnlyHtmlNode node);
    CSS_Declaration[] GetDeclarations();
}



public class Simple_CSSRule: I_CSSRule
{
    CSS_Declaration[] declarations;

    CSS_Declaration[] I_CSSRule.GetDeclarations()
    {
        return declarations.Clone() as CSS_Declaration[];
    }
    string _parentType, _type;

    IdSelector _parentId, _id;
    ClassSelector _parentClass, _class;

    AttributeSelector[] attrss;

    public Simple_CSSRule(string type = null, string id = null, string @class = null,
        string par_type = null, string par_id = null, string par_class = null,
        AttributeSelector[] atts = null,
        CSS_Declaration[] decs = null)
    {
        _type = type;
        if(id!=null)_id = new IdSelector(id);
        if(@class!=null)_class = new ClassSelector(@class);

        _parentType = par_type;
        if (par_id != null) _parentId = new IdSelector(par_id);
        if (par_class != null) _parentClass = new ClassSelector(par_class);

        if (atts != null) attrss = atts;
        else atts = new AttributeSelector[0];

        if (decs != null) declarations = decs;
        else declarations = new CSS_Declaration[0];
    }

    bool I_CSSRule.Match(ReadOnlyHtmlNode node)
    {
        if (_id!=null && !_id.IsMatch(node))return false;
        if (_class != null && !_class.IsMatch(node)) return false;
        if (_type != null && node.Name.ToLower() != _type.ToLower()) return false;
        if ((_parentClass != null || _parentId != null || _parentType != null) && node.Parent == null) return false;
        if (_parentClass != null && !_parentClass.IsMatch(node.Parent)) return false;
        if (_parentId != null && !_parentId.IsMatch(node.Parent)) return false;
        if (_parentType != null && node.Parent.Name.ToLower() != _parentType.ToLower()) return false;

        for (int i = 0; i < attrss.Length; i++)
        {
            if (!attrss[i].IsMatch(node))
                return false;
        }

        return true;
    }

    public override string ToString()
    {
        return "[type:" + (_type ?? "null") + " id: " + (_id == null ? "null" : _id.Value) + " class: " + (_class == null ? "null" : _class.Value) 
            + "[par_type: " + (_parentType ?? "null") + " par_id: " + (_parentId == null ? "null" : _parentId.Value) + " par_class: " + (_parentClass == null ? "null" : _parentClass.Value)
            + "]{ }";
    }
}


public class CSS_Declaration
{
    public string name;
    public string[] values;
}